package com.nicky.kids.Utility;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by NickZhang on 9/11/13.
 */
public class PhotoUtil {
    private static final String TAG = "nick_PhotoUtil";

    //计算图片的缩放值
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height/ (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            if (heightRatio < 0)
                inSampleSize = widthRatio;
            else if (widthRatio < 0)
                inSampleSize = heightRatio;
            else
                inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }


    public static Bitmap getFitBitmap(String filePath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }


//    public static Bitmap compress(String filePath, int reqWidth, int reqHeight) {
//        Bitmap bm = getFitBitmap(filePath, reqWidth, reqHeight);
//        ByteArrayOutputStream baos = null;
//        try{
//            baos = new ByteArrayOutputStream();
//            bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
//
////            int options = 100;
////            while ( baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
////                baos.reset();//重置baos即清空baos
////                bm.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
////                options -= 10;//每次都减少10
////            }
//        }finally{
//            try {
//                if(baos != null) {
//                    baos.flush();
//                    baos.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return bm;
//    }
}
